package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 用户账号服务
 *
 * @author ym
 * @date 2025/06/28 15:46
 */
@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;
    @Autowired
   private RechargeInfoMapper rechargeInfoMapper;
    /**
     * 保存用户帐户
     *
     * @param userId 用户ID
     */
    @Override
    public void saveUserAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(new BigDecimal("100"));
        userAccount.setAvailableAmount(new BigDecimal("100"));
        userAccount.setTotalIncomeAmount(new BigDecimal("100"));
        userAccountMapper.insert(userAccount);
        if (userAccount.getAvailableAmount().intValue() > 0) {
            this.saveUserAccountDetail(userId, "赠送", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, userAccount.getAvailableAmount(), null);
        }
    }

    /**
     * 保存用户帐户详细信息
     *
     * @param userId    用户ID
     * @param title     职称
     * @param tradeType 贸易类型
     * @param amount    金额
     * @param orderNo   订单号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 获得可用金额
     *
     * @param userId 用户ID
     * @return {@link BigDecimal}
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<UserAccount>().eq("user_id", userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);
        if (userAccount != null) {
            return userAccount.getAvailableAmount();
        }
        return null;
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void checkAndLock(Long userid, AccountLockVo accountLockVo) {

        String orderNo = accountLockVo.getOrderNo();
        Long userId = accountLockVo.getUserId();
        BigDecimal amount = accountLockVo.getAmount();
        String content = accountLockVo.getContent();
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserAccount account = userAccountMapper.selectOne(queryWrapper);
        if (account.getAvailableAmount().compareTo(accountLockVo.getAmount()) < 0) {
            throw new GuiguException(400, "账户余额不足");
        } else {
            int count = userAccountMapper.checkAndLock(userId, amount);
            //查看是否扣减成功
            if (count > 0) {
                //成功新增成功消费记录
                this.saveUserAccountDetail(userId, content, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, amount, orderNo);
            } else {
                throw new GuiguException(400, "账户扣费异常");
            }
        }


    }

    @Override
    public RechargeInfo getRechargeInfo(String orderNo, Long userId) {
        QueryWrapper<RechargeInfo> eq = new QueryWrapper<RechargeInfo>().eq("order_no", orderNo).eq("user_id", userId);
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(eq);
        if (rechargeInfo != null) {
            return rechargeInfo;
        }
        return null;
    }
}
